package com.gewu.bluetoothflow.adapter

import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.gewu.bluetoothflow.R
import com.gewu.bluetoothflow.bean.FlowCount
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList


class FlowDataAdatper(val context: Context) : RecyclerView.Adapter<FlowDataAdatper.ViewHolder>() {



    class ViewHolder(view: View) :RecyclerView.ViewHolder(view){
        val inData = view.findViewById<TextView>(R.id.in_data)
        val outData = view.findViewById<TextView>(R.id.out_data)
        val time = view.findViewById<TextView>(R.id.time_data)
    }


//    fun freshData(data: List<Historical>){
//        items = data
//        notifyDataSetChanged()
//    }
//     val dateFormat = SimpleDateFormat("yy-MM-dd HH", Locale.CHINA)  //:mm:ss
     private var items = ArrayList<FlowCount>()
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.flow_item,parent,false)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return items.size
    }

    @SuppressLint("ResourceAsColor")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        ////报警类型  1 正常  2 超过阀值  3 低于阀值
        val data = items[position]
        //Log.d("FlowDataAdapter","data:" + data.time + " in:"+data.`in` + "out: "+ data.out)
        holder.inData.text = data.`in`.toString()
        holder.outData.text = data.out.toString()
        if (data.time.length >= 8) {
            val date = data.time.substring(0, 2) + "-" + data.time.substring(
                2,
                4
            ) + "-" + data.time.substring(4, 6) + " " + data.time.substring(6, 8)
            holder.time.text = date //dateFormat.format(data.time)   //"24-08-12 14"
        }else{
            holder.time.text = data.time  //"24-08-12 14"
        }
    }

    fun setNewData(newData: ArrayList<FlowCount>) {
        val currentItemCount = itemCount
        if (currentItemCount != 0) {
            items.clear()
            notifyItemRangeRemoved(0, currentItemCount)
        }
        if (newData.isNotEmpty()) {
            items.addAll(newData)
            notifyItemRangeChanged(0, itemCount)
        }
    }

    fun addData(newData: ArrayList<FlowCount>) {
        val currentItemCount = itemCount
        if (newData.isNotEmpty()) {
            this.items.addAll(newData)
            notifyItemRangeChanged(currentItemCount, itemCount)
        }
    }




}